/*
 * 产投党建
 * 2018年8月8日17:14:35
 * xwx
 */

var ctdj = {

	api: {
		//获取、刷新token
		token: function() {
			var url = "http://" + localStorageFunc.get("config").server + ":" + localStorageFunc.get("config").port + "/";
			return url + "api/token";
		},
	},

	//	错误处理
	onError: function(message, status) {
		//	刷新token
		if(status == 401) {}
		mui.toast(message);
	},

	//	检查是否有网络
	checkConnection: function(callback) {
		if(plus.networkinfo.getCurrentType() == plus.networkinfo.CONNECTION_NONE) {
			callback(false);
		} else {
			callback(true);
		}
	},

	//	检查token是否过期
	checkToken: function(callback) {
		var token = localStorageFunc.get("token");
		//获取过期时间转换为时间戳
		var date = new Date(token[".expires"]);
		var timestamp_end = date.getTime();
		//获取当前时间
		var timestamp_now = Date.parse(new Date());
		//检查时间截止时间是否超出最大期限（提前10分钟刷新）
		if(timestamp_end - timestamp_now < 600) {
			//刷新token
			ctdj.refresh_token(token.refresh_token, function(r) {
				if(r) {
					//	更新本地缓存
					localStorageFunc.set("token", r);
					callback(r);
				}
			})
		} else {
			callback(token);
		}
	},

	//	刷新token
	refresh_token: function(token, callback) {
		mui.ajax({
			url: config.getToken,
			type: "POST",
			data: {
				"grant_type": "refresh_token",
				"refresh_token": token,
				"client_id": 'app',
				"client_secret": 'app',

			},
			error: function(r) {
				ctdj.onError("刷新token失败：" + r.statusText);
				//	回到首页
				callback(false);
				window.location.href = "login.html";
			},
			success: function(r) {
				localStorageFunc.set("token", r);
				callback(true);
			}
		});
	},

	//	检查是否登录
	checkLogin: function(callback) {
		if(localStorageFunc.get("token") == null) { //判断token
			callback(false);
		} else {
			callback(true);
		}
	},

	//	用户类模块
	user: {
		//	登录(获取token)
		login: function(username, password, callback) {

			//	判断设备有无网络
			ctdj.checkConnection(function(r) {
				if(!r) {
					ctdj.onError("网络异常，请检查网络设置！");
					return false;
				}
			});

			//	获取token信息
			mui.ajax({
				url: config.getToken,
				type: "POST",
				data: {
					"grant_type": "password",
					"username": username,
					"password": password,
					"client_id": 'app',
					"client_secret": 'app',
					"tenantid": 'default'
				},
				error: function(r) {
					//jczw.onError("登录失败：" + r.statusText);
					mui.toast("登录失败：" + r.statusText);
					callback(false);
				},
				success: function(r) {
					console.log('r' + JSON.stringify(r));
					localStorageFunc.set("token", r);
					callback(true);
				}
			});
		},

		//	通讯录信息
		getContacts: function(callback) {

			ctdj.checkToken(function(token) {
				mui.ajax({
					url: config.getContacts,
					type: "GET",
					headers: {
						"Access-Control-Allow-Headers": "X-Requested-With",
						"Authorization": "Bearer " + token.access_token
					},
					error: function(r) {
						ctdj.onError("获取通讯录失败：" + r.statusText);
						callback(false);
					},
					success: function(r) {
						callback(r);
					}
				});
			});
		},

		//	检索通讯录
		queryContacts: function(content, callback) {
			ctdj.checkToken(function(token) {
				var getUrl = config.queryContacts + '?queryUser=true&queryOrganization=true&search=' + content;
				mui.ajax({
					url: getUrl,
					type: "GET",
					headers: {
						"Access-Control-Allow-Headers": "X-Requested-With",
						"Authorization": "Bearer " + token.access_token
					},
					error: function(r) {
						ctdj.onError("检索通讯录失败：" + r.statusText);
						callback(r);
					},
					success: function(r) {
						callback(r);
					}
				});
			});
		},

		//	修改密码
		updatePassword: function(oldpwd, newpwd, callback) {

			ctdj.checkToken(function(token) {
				mui.ajax({
					url: config.updatePassword,
					data: {
						'oldpassword': oldpwd,
						'newpassword': newpwd
					},
					type: "POST",
					headers: {
						"Access-Control-Allow-Headers": "X-Requested-With",
						"Authorization": "Bearer " + token.access_token
					},
					error: function(r) {
						ctdj.onError("修改密码失败：" + r.statusText);
						callback(false);
					},
					success: function(r) {
						callback(r);
					}
				})

			});

		}
	},

	//	CMS模块
	cms: {

		//	获取首页推荐
		getCommendatory: function(callback) {

			ctdj.checkToken(function(token) {
				mui.ajax({
					url: config.getCommendatoryArticles,
					type: "GET",
					headers: {
						"Access-Control-Allow-Headers": "X-Requested-With",
						"Authorization": "Bearer " + token.access_token
					},
					error: function(r) {
						mui.toast("获取推荐文章失败" + r.statusText);
						callback(false);
					},
					success: function(r) {
						callback(r);
					}
				});
			});

		},

		//	获取资讯新闻列表
		getList: function(colId, selforg, skip, count, callback) {
			var geturl = config.getList + "?columnId=" + colId + "&selfOrganization=" + selforg + "&skipCount=" + skip + "&maxResultCount=" + count;
			ctdj.checkToken(function(token) {
				mui.ajax({
					url: geturl,
					type: "GET",
					headers: {
						"Access-Control-Allow-Headers": "X-Requested-With",
						"Authorization": "Bearer " + token.access_token
					},
					error: function(r) {
						mui.toast("获取推荐文章失败" + r.statusText);
						callback(false);
					},
					success: function(r) {
						callback(r);
					}
				});
			});

		},

		//	检索文章
		queryArticle: function(content, id, skipCount, maxResultCount, callback) {
			var geturl = config.queryArticle + "?search=" + content + "&columnid=" + id + "&skipCount=" + skipCount + "&maxResultCount=" + maxResultCount;
			//console.log(geturl);
			ctdj.checkToken(function(token) {
				mui.ajax({
					url: geturl,
					type: "GET",
					headers: {
						"Access-Control-Allow-Headers": "X-Requested-With",
						"Authorization": "Bearer " + token.access_token
					},
					error: function(r) {
						mui.toast("获取检索文章失败" + r.statusText);
						callback(false);
					},
					success: function(r) {
						callback(r);
					}
				});
			});

		},

		//	查看新闻详情
		getArticle: function(id, callback) {
			var geturl = config.getArticle + "?id=" + id;
			ctdj.checkToken(function(token) {
				mui.ajax({
					url: geturl,
					type: "GET",
					headers: {
						"Access-Control-Allow-Headers": "X-Requested-With",
						"Authorization": "Bearer " + token.access_token
					},
					error: function(r) {
						mui.toast("获取文章失败" + r.statusText);
						callback(false);
					},
					success: function(r) {
						r.result.body = ctdj.tools.handleArticleBodyImageUrl(r.result.body);
						callback(r);
					}
				});
			});
		},

		//	点赞
		setLike: function(id, callback) {
			ctdj.checkToken(function(token) {
				mui.ajax({
					url: config.setLike + '?id=' + id,
					type: "POST",
					headers: {
						"Access-Control-Allow-Headers": "X-Requested-With",
						"Authorization": "Bearer " + token.access_token
					},
					error: function(r) {
						mui.toast("点赞失败" + r.statusText);
						callback(false);
					},
					success: function(r) {
						callback(r);
					}
				});
			});
		},

		//	取消点赞
		setUnLike: function(id, callback) {
			ctdj.checkToken(function(token) {
				mui.ajax({
					url: config.setUnLike + '?id=' + id,
					type: "POST",
					headers: {
						"Access-Control-Allow-Headers": "X-Requested-With",
						"Authorization": "Bearer " + token.access_token
					},
					error: function(r) {
						mui.toast("取消点赞失败" + r.statusText);
						callback(false);
					},
					success: function(r) {
						callback(r);
					}
				});
			});
		},

		//	获取文章点赞记录
		getLikedUsers: function(articleid, maxResultCount, callback) {
			var geturl = config.getLikedUsers + "?articleid=" + articleid + "&skipCount=" + skipCount + "&maxResultCount=" + maxResultCount;
			ctdj.checkToken(function(token) {
				mui.ajax({
					url: geturl,
					type: "GET",
					headers: {
						"Access-Control-Allow-Headers": "X-Requested-With",
						"Authorization": "Bearer " + token.access_token
					},
					error: function(r) {
						mui.toast("获取文章点赞记录失败" + r.statusText);
						callback(false);
					},
					success: function(r) {
						callback(r);
					}
				});
			});

		},

		//	评论
		setPost: function(articleid, parentid, content, callback) {
			ctdj.checkToken(function(token) {
				mui.ajax({
					url: config.setPost,
					type: "POST",
					data: {
						"articleid": articleid,
						"parentid": parentid,
						'content': content
					},
					headers: {
						"Access-Control-Allow-Headers": "X-Requested-With",
						"Authorization": "Bearer " + token.access_token
					},
					error: function(r) {
						mui.toast("添加评论失败" + r.statusText);
						callback(false);
					},
					success: function(r) {
						callback(r);
					}
				});
			});
		},

		//	删除评论
		removePost: function(articleid, commentid, callback) {
			ctdj.checkToken(function(token) {
				mui.ajax({
					url: config.removePost,
					type: "POST",
					data: {
						"articleid": articleid,
						"commentid": commentid,
					},
					headers: {
						"Access-Control-Allow-Headers": "X-Requested-With",
						"Authorization": "Bearer " + token.access_token
					},
					error: function(r) {
						mui.toast("删除评论失败" + r.statusText);
						callback(false);
					},
					success: function(r) {
						callback(r);
					}
				});
			});
		},

		//	获取评论
		getComLike: function(articleid, skipCount, maxResultCount, callback) {
			var geturl = config.getComLike + "?articleid=" + articleid + "&skipCount=" + skipCount + "&maxResultCount=" + maxResultCount;
			ctdj.checkToken(function(token) {
				mui.ajax({
					url: geturl,
					type: "GET",
					headers: {
						"Access-Control-Allow-Headers": "X-Requested-With",
						"Authorization": "Bearer " + token.access_token
					},
					error: function(r) {
						mui.toast("获取评论记录失败" + r.statusText);
						callback(false);
					},
					success: function(r) {
						callback(r);
					}
				});
			});

		},

		//	给评论点赞
		setComlike: function(articleid, commentid, callback) {
			ctdj.checkToken(function(token) {
				mui.ajax({
					url: config.setComlike,
					type: "POST",
					data: {
						"articleid": articleid,
						"commentid": commentid
					},
					headers: {
						"Access-Control-Allow-Headers": "X-Requested-With",
						"Authorization": "Bearer " + token.access_token
					},
					error: function(r) {
						mui.toast("给评论点赞失败" + r.statusText);
						callback(false);
					},
					success: function(r) {
						callback(r);
					}
				});
			});
		},

		//	删除评论的赞
		delComunlike: function(commentid, callback) {
			ctdj.checkToken(function(token) {
				mui.ajax({
					url: config.delComunlike + '?commentid=' + commentid,
					type: "POST",
					headers: {
						"Access-Control-Allow-Headers": "X-Requested-With",
						"Authorization": "Bearer " + token.access_token
					},
					error: function(r) {
						mui.toast("删除评论的赞失败" + r.statusText);
						callback(false);
					},
					success: function(r) {
						callback(r);
					}
				});
			});
		},

		//	获取评论的点赞记录
		getComLikeUsers: function(commentid, skipCount, maxResultCount, callback) {
			var geturl = config.getComLikeUsers + "?commentid=" + commentid + "&skipCount=" + skipCount + "&maxResultCount=" + maxResultCount;
			ctdj.checkToken(function(token) {
				mui.ajax({
					url: geturl,
					type: "GET",
					headers: {
						"Access-Control-Allow-Headers": "X-Requested-With",
						"Authorization": "Bearer " + token.access_token
					},
					error: function(r) {
						mui.toast("获取评论的点赞记录失败" + r.statusText);
						callback(false);
					},
					success: function(r) {
						callback(r);
					}
				});
			});

		},

	},

	//	群聊模块
	group: {

		//	获取群列表
		getGroup: function(callback) {
			ctdj.checkToken(function(token) {
				mui.ajax({
					url: config.getGroup,
					type: "GET",
					headers: {
						"Access-Control-Allow-Headers": "X-Requested-With",
						"Authorization": "Bearer " + token.access_token
					},
					error: function(r) {
						mui.toast("获取群聊列表失败" + r.statusText);
						callback(false);
					},
					success: function(r) {
						callback(r);
					}
				});
			});
		},

		//	创建群
		createGroup: function(name, userids, callback) {
			ctdj.checkToken(function(token) {
				mui.ajax({
					url: config.createGroup,
					type: "POST",
					data: {
						"name": name,
						"userids": userids,
					},
					headers: {
						"Access-Control-Allow-Headers": "X-Requested-With",
						"Authorization": "Bearer " + token.access_token
					},
					error: function(r) {
						mui.toast("创建群聊失败" + r.statusText);
						callback(false);
					},
					success: function(r) {
						callback(r);
					}
				});
			});
		},

		//	修改群名称
		renameGroup: function(groupid, name, callback) {
			ctdj.checkToken(function(token) {
				mui.ajax({
					url: config.renameGroup,
					type: "POST",
					data: {
						"name": name,
						"groupid": groupid,
					},
					headers: {
						"Access-Control-Allow-Headers": "X-Requested-With",
						"Authorization": "Bearer " + token.access_token
					},
					error: function(r) {
						mui.toast("修改群名称失败" + r.statusText);
						callback(false);
					},
					success: function(r) {
						callback(r);
					}
				});
			});
		},

		//	邀请成员
		inviteUserGroup: function(groupid, userids, callback) {
			ctdj.checkToken(function(token) {
				mui.ajax({
					url: config.inviteUserGroup,
					type: "POST",
					data: {
						"userids": userids,
						"groupid": groupid,
					},
					headers: {
						"Access-Control-Allow-Headers": "X-Requested-With",
						"Authorization": "Bearer " + token.access_token
					},
					error: function(r) {
						mui.toast("邀请群成员失败" + r.statusText);
						callback(false);
					},
					success: function(r) {
						callback(r);
					}
				});
			});
		},

		//	移除成员
		removeUserGroup: function(groupid, userids, callback) {
			ctdj.checkToken(function(token) {
				mui.ajax({
					url: config.removeUserGroup,
					type: "POST",
					data: {
						"userids": userids,
						"groupid": groupid,
					},
					headers: {
						"Access-Control-Allow-Headers": "X-Requested-With",
						"Authorization": "Bearer " + token.access_token
					},
					error: function(r) {
						mui.toast("移除群成员失败" + r.statusText);
						callback(false);
					},
					success: function(r) {
						callback(r);
					}
				});
			});
		},

		//	退群
		exitGroup: function(groupid, callback) {
			ctdj.checkToken(function(token) {
				mui.ajax({
					url: config.exitGroup + '?groupid=' + groupid,
					type: "POST",
					headers: {
						"Access-Control-Allow-Headers": "X-Requested-With",
						"Authorization": "Bearer " + token.access_token
					},
					error: function(r) {
						mui.toast("退群失败" + r.statusText);
						callback(false);
					},
					success: function(r) {
						callback(r);
					}
				});
			});
		},
	},

	//	IM模块
	im: {

		//	获取单聊记录
		getSingleChatMsgs: function(id, offset, limit, callback) {
			var path = config.getSingleChatMsgs + '?userid=' + id + '&skipCount=' + offset + '&maxResultCount=' + limit;
			//console.log('path=' + path);

			ctdj.checkToken(function(token) {
				mui.ajax({
					url: path,
					type: "GET",
					headers: {
						"Access-Control-Allow-Headers": "X-Requested-With",
						"Authorization": "Bearer " + token.access_token
					},
					error: function(r) {
						mui.toast("获取单聊记录失败" + r.statusText);
						callback(false);
					},
					success: function(r) {
						callback(r);
					}
				});
			});
		},

		//	获取群聊记录
		getGroupChatMsgs: function(id, offset, limit, callback) {
			var path = config.getGroupChatMsgs + '?groupid=' + id + '&skipCount=' + offset + '&maxResultCount=' + limit;
			ctdj.checkToken(function(token) {
				mui.ajax({
					url: path,
					type: "GET",
					headers: {
						"Access-Control-Allow-Headers": "X-Requested-With",
						"Authorization": "Bearer " + token.access_token
					},
					error: function(r) {
						mui.toast("获取群聊记录失败" + r.statusText);
						callback(false);
					},
					success: function(r) {
						callback(r);
					}
				});

			});
		},

	},

	//	工作流模块
	workflow: {

		//	获取待办
		getworks: function(search, business, type, offset, limit, callback) {
			var path = config.getworks + '?search=' + search + '&business=' + business + '&type=' + type + '&skipCount=' + offset + '&maxResultCount=' + limit;
			console.log('path:' + path);
			ctdj.checkToken(function(token) {
				mui.ajax({
					url: path,
					type: "GET",
					headers: {
						"Access-Control-Allow-Headers": "X-Requested-With",
						"Authorization": "Bearer " + token.access_token
					},
					error: function(r) {
						mui.toast("获取待办失败" + r.statusText);
						callback(false);
					},
					success: function(r) {
						callback(r);
					}
				});
			})
		},

		//	处理待办
		handle: function(workid, nodeid, status, disagreeHandleType, description, callback) {
			ctdj.checkToken(function(token) {
				mui.ajax({
					url: config.handle,
					type: "POST",
					data: {
						"workid": workid,
						"nodeid": nodeid,
						"status": status,
						'disagreeHandleType': disagreeHandleType,
						"description": description,
					},
					headers: {
						"Access-Control-Allow-Headers": "X-Requested-With",
						"Authorization": "Bearer " + token.access_token
					},
					error: function(r) {
						mui.toast("处理待办失败" + r.statusText);
						callback(false);
					},
					success: function(r) {
						callback(r);
					}
				});
			})
		},
		
		//	获取办理记录
		getHandleRecord: function(workid, callback) {
			var geturl = config.getHandleRecord + "?workid=" + workid;
			ctdj.checkToken(function(token) {
				mui.ajax({
					url: geturl,
					type: "GET",
					headers: {
						"Access-Control-Allow-Headers": "X-Requested-With",
						"Authorization": "Bearer " + token.access_token
					},
					error: function(r) {
						mui.toast("获取办理记录失败" + r.statusText);
						callback(false);
					},
					success: function(r) {
						callback(r);
					}
				});
			});
		},

	},

	// 工具类
	tools: {

		//	版本检查更新
		checkAppVersion: function(type, version, callback) {
			var geturl = config.getVersion + '?client=' + type + '&version=' + version;
			//console.log(geturl);
			ctdj.checkToken(function(token) {
				mui.ajax({
					type: "GET",
					data: '',
					url: geturl,
					headers: {
						"Access-Control-Allow-Headers": "X-Requested-With",
						"Authorization": "Bearer " + token.access_token
					},
					error: function(r) {
						//errorHandle(xhr, type, errorThrown, error);
						callback(r);
					},
					success: function(r) {
						callback(r);
					}
				});
			});

		},

		//	相对路径转换绝对路径
		handelImageFullUrl: function(url) {
			return config.getIp + url;
		},

		//	内容详情图片地址转换
		handleArticleBodyImageUrl: function(url) {

			// 匹配img 标签内第一个属性是src   如遇不是src的路径转换就会失败
			/*var reg = new RegExp("<img src=\"", "g");
			var newUrl = url.replace(reg, '<img data-preview-src="" data-preview-group="1" src="' + config.getIp + '');
			return  newUrl;
			*/

			//	匹配所有标签 查找标签内属性是src 更换为绝对路径var reg = /<img(.*?)src="([^"]+)"/gi; 只匹配img 标签
			var str = url;
			var reg = /<(.*?)src="([^"]+)"/gi;
			var newUrl;
			var preUrl;
			str = str.replace(reg, function(img, attrs, src) {
				//newUrl = 'src="' + src;
				//console.log('图片预处理src=' + src);
				if(!((src.indexOf('http://') == 0) || (src.indexOf('https://') == 0))) { // 相对路径
					/*preUrl = config.getIp + src; //原图大小
					newUrl = 'src="' + config.getIp + src; //预览图
					newUrl = 'src="' + config.getIp + ctdj.tools.thumbImage(src); //预览图
					*/
					if(src.indexOf(".thumb") > 0) { // 判断是否是缩略图 ,存在缩略图就整理大图
						newUrl = 'src="' + config.getIp + src; //预览图
						preUrl = config.getIp + src.replace('.thumb', ''); //原图大小
					} else { // 默认是大图
						newUrl = 'src="' + config.getIp + src; //预览图
						preUrl = config.getIp + src; //原图大小
					}
				} else { //绝对路径
					if(src.indexOf(".thumb") > 0) { // 判断是否是缩略图 ,存在缩略图就整理大图
						newUrl = 'src="' + src; //预览图
						preUrl = src.replace('.thumb', ''); //原图大小
					} else { // 默认是大图
						newUrl = 'src="' + src; //预览图
						preUrl = src; //原图大小
					}
				}
				return '<' + attrs + newUrl + '" data-preview-src="' + preUrl + '" data-preview-group="1"';
			})
			return str;
		},

		//	图片路径转换缩略图
		thumbImage: function(imgPath) {
			var extStrat = imgPath.lastIndexOf('.');
			//var ext = imgPath.substring(extStrat, imgPath.length).toUpperCase();
			var thumbpath = imgPath.substring(0, extStrat) + '.thumb' + imgPath.substring(extStrat, imgPath.length);
			return thumbpath;
		}

	}

}